import requestAxios from '@/assets/js/axios.js'

let api = '/tool/send_raw_transaction.do';

let Web3 = require("web3");
let Tx = require('ethereumjs-tx').Transaction

// 创建web3对象
// let web3 = new Web3('https://mainnet.infura.io/v3/44cb835e6800434fb1c0404af0ba96bf')
let web3 = new Web3()

export default {

    getETHBalance(address) {
        web3.eth.getBalance(address).then(console.log)
    },

    getTransactionInfo(address, callback) {
        return requestAxios.requestCMS('post', '/tool/get_transaction_info.do', {
            address: address
        }, callback)
    },

    sendTokenTx(params, callback) {
        console.log('sendTokenTx params===', params)
        this.getTransactionInfo(params.from, data => {
            console.log('data = ', data)
            let nonce = parseInt(data.data.nonce)
            let gasPrice = parseInt(data.data.price)
            this.sendTokenTxWithNonce(nonce, gasPrice, params, callback)
        })
    },

    batchSendTokenTx(from, array, callback) {
        console.log('batchSendTokenTx params===', array)
        this.getTransactionInfo(from, data => {
            console.log('data = ', data)
            let nonce = parseInt(data.data.nonce)
            let gasPrice = parseInt(data.data.price)
            for(let i in array) {
                this.sendTokenTxWithNonce(nonce++, gasPrice, array[i], callback)
            }
        })
    },

    sendTokenTxWithNonce(nonce, gasPrice, params, callback) {
        let {privateKey, from, contractAddress, toAddress, count, gasLimit} = params
        gasPrice = gasPrice * (params.gasPrice || 1)
        // gasPrice = 1000
        // gasLimit = 1
        count = count * 1e18
        console.log('nonce = ', nonce,
            ', gasPrice = ', gasPrice,
            ', gasLimit = ', gasLimit,
            ', gas = ', gasPrice * gasLimit,
            ', count = ', count)
        var txData = {
            nonce: web3.utils.toHex(nonce),
            gasLimit: web3.utils.toHex(gasLimit),
            // gasPrice: web3.utils.toHex(gasPrice),
            gasPrice: gasPrice,
            from: from,
            // 注意这里是代币合约地址
            to: contractAddress,
            // 调用合约转账value这里留空
            value: web3.utils.toHex(0),
            // data的组成，由：0x + 要调用的合约方法的function signature + 要传递的方法参数，每个参数都为64位(对transfer来说，第一个是接收人的地址去掉0x，第二个是代币数量的16进制表示，去掉前面0x，然后补齐为64位)
            data: '0x' + 'a9059cbb' + this.addPreZero(toAddress.substr(2)) + this.addPreZero(web3.utils.toHex(count).substr(2))
        }
        console.log('txData = ', JSON.stringify(txData))
        // return
        var tx = new Tx(txData)
        const key = new Buffer(privateKey.substr(2), 'hex')
        tx.sign(key)
        let serializedTx = tx.serialize().toString('hex')
        let signData = '0x' + serializedTx
        if(params.id) {
            requestAxios.requestCMS('post', '/manager/user_balance_record/send_raw_transaction.do', {
                data: signData,
                recordId: params.id
            }, function (data) {
                callback(data, params)
            })
        }else {
            requestAxios.requestCMS('post', '/tool/send_raw_transaction.do', {
                data: signData
            }, function (data) {
                callback(data, params)
            })
        }
    },


    batchSendETHTx(from, array, callback) {
        console.log('batchSendTokenTx params===', array)
        this.getTransactionInfo(from, data => {
            console.log('data = ', data)
            let nonce = parseInt(data.data.nonce)
            let gasPrice = parseInt(data.data.price)
            for(let i in array) {
                this.sendETHTxWithNonce(nonce++, gasPrice, array[i], callback)
            }
        })
    },

    sendETHTxWithNonce(nonce, gasPrice, params, callback) {
        let {privateKey, from, toAddress, count, gasLimit} = params
        gasPrice = gasPrice * (params.gasPrice || 1)
        count = count * 1e18
        console.log('nonce = ', nonce,
            ', gasPrice = ', gasPrice,
            ', gasLimit = ', gasLimit,
            ', gas = ', gasPrice * gasLimit,
            ', count = ', count)
        var txData = {
            nonce: web3.utils.toHex(nonce),
            gasLimit: web3.utils.toHex(gasLimit),
            gasPrice: gasPrice,
            from: from,
            to: toAddress,
            value: web3.utils.toHex(count),
            data: ''
        }
        console.log('ETH txData = ', JSON.stringify(txData))
        var tx = new Tx(txData)
        const key = new Buffer(privateKey.substr(2), 'hex')
        tx.sign(key)
        let serializedTx = tx.serialize().toString('hex')
        let signData = '0x' + serializedTx
        requestAxios.requestCMS('post', '/tool/send_raw_transaction.do', {
            data: signData
        }, function (data) {
            callback(data, params)
        })
    },

    async sendETHTx(params, callback) {
        this.getTransactionInfo(params.from, data => {
            console.log('data = ', data)
            let nonce = parseInt(data.data.nonce)
            let gasPrice = parseInt(data.data.price)
            let {privateKey, from, toAddress, count, gasLimit} = params
            gasPrice = gasPrice * (params.gasPrice || 1)
            console.log('gas = ' + (gasPrice * gasLimit + count * 1e18))
            var txData = {
                nonce: web3.utils.toHex(nonce),
                gasLimit: web3.utils.toHex(gasLimit),
                gasPrice: gasPrice,
                from: from,
                to: toAddress,
                value: web3.utils.toHex(count * 1e18),
                data: ''
            }
            console.log('ETH txData = ', JSON.stringify(txData))
            var tx = new Tx(txData)
            const key = new Buffer(privateKey.substr(2), 'hex')
            tx.sign(key)
            let serializedTx = tx.serialize().toString('hex')
            let signData = '0x' + serializedTx
            requestAxios.requestCMS('post', '/tool/send_raw_transaction.do', {
                data: signData
            }, function (data) {
                callback(data, params)
            })
        })

        // web3.eth.sendSignedTransaction('0x' + serializedTx, (error, hash) => {
        //     if (!error) {
        //         console.log('hash = ' + hash)
        //         if (callback) {
        //             callback({params: params, hash: hash})
        //         }
        //     } else {
        //         console.log('error = ', error)
        //         if (callback) {
        //             callback({params: params})
        //         }
        //     }
        // })
    },

    // 补齐64位，不够前面用0补齐
    addPreZero(num) {
        var t = (num + '').length,
            s = '';
        for (var i = 0; i < 64 - t; i++) {
            s += '0';
        }
        return s + num;
    },

    getTx() {
        var addr = "0xbfb2e296d9cf3e593e79981235aed29ab9984c0f"
        var filter = web3.eth.filter({fromBlock: 0, toBlock: 'latest', address: addr});
        filter.get(function (err, transactions) {
            transactions.forEach(function (tx) {
                var txInfo = web3.eth.getTransaction(tx.transactionHash);
                //这时可以将交易信息txInfo存入数据库
            });
        });
    }
}
